import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { find } from 'lodash-es'
import baseRouter from './modules/base-router'
import pcRouter from './modules/pc-router'
import mobileRouter from './modules/mobile-router'
import redirect from '@/views/app/redirect/index.vue'
import { bus, isPC, showWarning, t } from '@/utils'
import { useAccountStore, useAppStore, useWalletStore } from '@/store'
import { LangList } from '@/enums'
//import { AccountShowType } from '@/types'
declare module 'vue-router' {
	interface RouteMeta {
		menu?: boolean
		title?: string
		icon?: string
		class?: string
		auth?: boolean
	}
}

export const publicRoutes: Array<RouteRecordRaw> = [
	...baseRouter,
	...(isPC() ? pcRouter : mobileRouter),
	{
		path: '/:pathMatch(.*)*',
		component: redirect
	}
]

export const router = createRouter({
	history: createWebHistory(),
	routes: publicRoutes,
	scrollBehavior() {
		// 始终滚动到顶部
		return { top: 0 }
	}
})

/**
 * 加载错误时刷新页面;
 */
router.onError((error, to) => {
	if (String(error).includes('TypeError: Failed to fetch dynamically imported module')) {
		const newTo = router.resolve({ ...to })
		window.location.href = newTo.fullPath
	}
})

router.beforeEach((to: any, from, next) => {
	const appStore = useAppStore()
	const accountStore = useAccountStore()
	const lang = to.params.locale || to.params.pathMatch?.[0]
	if (LangList.includes(lang)) {
		appStore.setLang(lang)
	}
	if (to.name !== from.name) {
		bus.$emit('SCROLLTOP')
	} else {
		bus.$emit('SCROLLTOP')
	}
	if (to.path === '/todo') {
		showWarning(t('app.todo'))
		return next(from)
	}
	if (to.meta?.needLogin && !accountStore.isLogin) {
		// 这里统一拦截需要登录才能进的路由, 在配置里添加 `meta: { needLogin: true }` 即可
		if (to.name === 'settings' || find(to.matched, { name: 'settings' })) {
			accountStore.showLogin()
		}
		return next('/')
	}
	next()
})
router.afterEach((to) => {
	const appStore = useAppStore()
	const accountStore = useAccountStore()

	const queryTab = to.query?.tab
	const modal = to.query?.modal
	const agentCode = to.query?.r

	if (queryTab === 'login') {
		useAccountStore().showLogin()
	} else if (queryTab === 'register') {
		useAccountStore().showRegister()
	}

	if (modal === 'wallet-deposit') {
		useWalletStore().showWalletDeposit()
	} else if (queryTab === 'withdraw-crypto' && modal === 'wallet-withdraw') {
		useWalletStore().showWalletWithdraw()
	}
	if (modal === 'wallet-settings') {
		useWalletStore().showWalletSetting()
	}

	if (agentCode && !accountStore.isLogin) {
		useAccountStore().showRegister()
		//accountStore.showAccount(AccountShowType.register)
	}
	appStore.setCasinoDetailVisible(false, null)

	appStore.showMobileMenu(false)
})
/* 初始化路由表 */
export function resetRouter() {
	router.getRoutes().forEach((route) => {
		const { name } = route
		if (name) {
			router.hasRoute(name) && router.removeRoute(name)
		}
	})
}

export default router
